package basics;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import miniBanco.Exceptions.HandledSQLException;

public  class MySqlHelper {
	//ES SINGLETON NO?
	
	private static MySqlHelper instance = null;

	private MySqlHelper() {};
	
	public static MySqlHelper getInstance() {
		  if(instance == null) {
		     instance = new MySqlHelper();
		  }
		  return instance;
	}
	
	public void ExecuteNonQuery(String sql,String TAG)
	{
		ExecuteNonQuery(sql);
		DBManager.Log(TAG, String.format("Ejecute comando sql. sql:%s", sql));
	}

	public void ExecuteNonQuery(String sql) {
		Connection c = DBManager.connect();
		try {
			Statement s = c.createStatement();
			s.executeUpdate(sql);
			c.commit();
		} catch (SQLException e) {
			try {
				c.rollback();
				DBManager.Error(e);
				throw new HandledSQLException("Se produjo un error al ejecutar el comando sql. Ver Log de Erores.");
			} catch (SQLException ex) {
				DBManager.Error(ex);
				throw new HandledSQLException("Se produjo un error al hacer el rollback. Ver Log de Erores.");
			}
		} 
	}
	
	public ResultSet ExecuteQuery(String sql,String TAG)
	{
		Connection c = DBManager.connect();
		try {
			Statement s = c.createStatement();
			ResultSet rs = s.executeQuery(sql);
			
			DBManager.Log(TAG, String.format("Ejecute comando sql. sql:%s", sql));
			return rs;
			
		} catch (SQLException ex) {
				DBManager.Error(ex);
				try {
					c.rollback();
				} catch (SQLException e) {
					DBManager.Error(e);
					throw new HandledSQLException("Se produjo un error al hacer el rollback :(.");
				}
				throw new HandledSQLException(ex.getMessage());

		} finally {
				try {
					c.close();
				} catch (SQLException e) {
					DBManager.Error(e);
					throw new HandledSQLException("Se produjo un error al cerrar la conexion.");
				}
		}

	}

}
